
#include "stdafx.h"
#include "google_auth.h"

#pragma comment(lib, "wininet")

#define BUFFER_SIZE	1024


GoogleAuth::GoogleAuth()
{

}

GoogleAuth::GoogleAuth(CStringA const& strService)
:m_strService(strService)
{
	
}

GoogleAuth::~GoogleAuth()
{
	
}

BOOL GoogleAuth::Login( CStringA const& strEmail, CStringA const& strPasswd )
{
	m_hInternet = InternetOpen(L"iRing-Client", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	if (NULL != m_hInternet)
	{
		m_hSession = InternetConnect(m_hInternet, 
			L"www.google.com", 443, L"", L"", INTERNET_SERVICE_HTTP, 0, 0);

		DWORD dwSecureFlag =	INTERNET_FLAG_RELOAD | 
								INTERNET_FLAG_KEEP_CONNECTION |
								INTERNET_FLAG_NO_CACHE_WRITE| 
								INTERNET_FLAG_SECURE |
								INTERNET_FLAG_IGNORE_CERT_CN_INVALID;

		CStringA strAuthData("accountType=HOSTED_OR_GOOGLE&");
		strAuthData.AppendFormat("Email=%s&", strEmail);
		strAuthData.AppendFormat("Passwd=%s&", strPasswd);
		strAuthData.AppendFormat("service=%s&", m_strService);
		strAuthData.AppendFormat("source=%s", "iRing-Client");

		HINTERNET hAuthRequest = HttpOpenRequest(m_hSession, L"POST", L"/accounts/ClientLogin", NULL, NULL, NULL, dwSecureFlag, 0); 
		if (NULL != hAuthRequest)
		{
			HttpAddRequestHeaders(hAuthRequest, L"Content-type: application/x-www-form-urlencoded\r\n", -1L, HTTP_ADDREQ_FLAG_ADD_IF_NEW); 

			BOOL bSuccess = HttpSendRequest(hAuthRequest, NULL, NULL, (LPVOID)(LPCSTR)strAuthData, strAuthData.GetLength()); 
			if (bSuccess)
			{
				CStringA strResult;

				DWORD dwNumberOfBytesRead = 0;
				char szResult[BUFFER_SIZE] = {};

				do
				{ 
					BOOL bRead = InternetReadFile(hAuthRequest, szResult, 1024, &dwNumberOfBytesRead); 
					szResult[dwNumberOfBytesRead] = '\0';
					
					strResult += szResult;
					ZeroMemory(szResult, BUFFER_SIZE);
				} while(!strResult.IsEmpty() && dwNumberOfBytesRead != 0);

				int iPos = strResult.Find("Auth=");
				if (iPos >= 0)
				{
					m_strToken = strResult.Right(strResult.GetLength() - iPos - 5);
					m_strToken.Trim();
				}
			}

			InternetCloseHandle(hAuthRequest);
		}
		
	}
	return TRUE;
}

void GoogleAuth::SetService( CStringA const& strService )
{
	ATLASSERT( m_strService.IsEmpty() );
	m_strService = strService;
}